import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/db'
import { getUserFromRequest } from '@/lib/auth'
import axios from 'axios'

// TikTok数据采集接口
export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const user = getUserFromRequest(request)
    if (!user) {
      return NextResponse.json(
        { error: '未授权访问' },
        { status: 401 }
      )
    }

    const { videoUrl } = await request.json()

    if (!videoUrl) {
      return NextResponse.json(
        { error: '视频URL不能为空' },
        { status: 400 }
      )
    }

    // 从URL中提取视频ID
    const videoId = extractVideoIdFromUrl(videoUrl)
    if (!videoId) {
      return NextResponse.json(
        { error: '无效的TikTok视频URL' },
        { status: 400 }
      )
    }

    // 检查视频是否已存在
    const existingVideo = await prisma.tikTokVideo.findUnique({
      where: { videoId }
    })

    if (existingVideo) {
      return NextResponse.json({
        message: '视频已存在',
        video: existingVideo
      })
    }

    // 调用TikTok API获取视频信息
    const videoData = await fetchTikTokVideoData(videoId)

    // 保存视频信息到数据库
    const video = await prisma.tikTokVideo.create({
      data: {
        videoId,
        url: videoUrl,
        title: videoData.title,
        description: videoData.description,
        author: videoData.author,
        authorId: videoData.authorId,
        likes: videoData.likes,
        shares: videoData.shares,
        comments: videoData.comments,
        views: videoData.views,
        duration: videoData.duration
      }
    })

    return NextResponse.json({
      message: '视频数据采集成功',
      video
    })

  } catch (error) {
    console.error('TikTok collect error:', error)
    return NextResponse.json(
      { error: '数据采集失败' },
      { status: 500 }
    )
  }
}

// 从TikTok URL中提取视频ID
function extractVideoIdFromUrl(url: string): string | null {
  try {
    const patterns = [
      /tiktok\.com\/@[\w.-]+\/video\/(\d+)/,
      /tiktok\.com\/v\/(\d+)/,
      /vm\.tiktok\.com\/(\w+)/
    ]

    for (const pattern of patterns) {
      const match = url.match(pattern)
      if (match) {
        return match[1]
      }
    }
    return null
  } catch {
    return null
  }
}

// 调用TikTok API获取视频数据（模拟实现）
async function fetchTikTokVideoData(videoId: string) {
  // 这里应该调用实际的TikTok API
  // 由于TikTok API的限制，这里提供一个模拟实现
  
  try {
    // 模拟API调用
    // 实际项目中需要替换为真实的TikTok API调用
    const mockData = {
      title: `TikTok Video ${videoId}`,
      description: '这是一个TikTok视频的描述',
      author: 'test_user',
      authorId: 'test_user_id',
      likes: Math.floor(Math.random() * 10000),
      shares: Math.floor(Math.random() * 1000),
      comments: Math.floor(Math.random() * 500),
      views: Math.floor(Math.random() * 100000),
      duration: Math.floor(Math.random() * 60) + 15
    }

    return mockData
  } catch (error) {
    console.error('Failed to fetch TikTok data:', error)
    throw new Error('Failed to fetch video data')
  }
}
